package com.sd.repay.channel.cj;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sd.repay.cache.BankCache;
import com.sd.repay.channel.cj.util.EncryptUtil;
import com.sd.repay.channel.cj.util.SignUtil;
import com.sd.repay.common.CommonResult;
import com.sd.repay.common.Constants;
import com.sd.repay.pojo.ZqMerchant;
import com.sd.repay.service.BindCardService;
import com.sd.repay.service.ZqMerchantService;
import com.sd.repay.utils.*;
import okhttp3.MediaType;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author sd
 * @Description: 畅捷业务实现类
 * @date 2018年09月04日
 */
public class CJBusinessImpl {

    private static Logger log = LoggerFactory.getLogger(CJBusinessImpl.class);
    public static final MediaType medidType = MediaType.parse("application/json; charset=utf-8");

    //畅捷统一请求地址
    public static final String CJ_ACCESS_URL = WebUtil.getSysValue("CJ_ACCESS_URL");
    //畅捷服务商编号
    public static String CJ_SP_CODE;
    //畅捷服务商密钥
    public static String CJ_MER_KEY;
    //畅捷渠道编号
    public static String CJ_CHANNEL_CODE;
    //交易费率
    public static String CJ_FEE_RATE;
    //单笔代付成本
    public static String CJ_SINGLE_FEE;

    static {
        Map<String, Object> cjChannel = WebUtil.getPayChannelInfo(Constants.PAY_ACQ_CODE_CJ);
        log.info("畅捷通道信息：" + JsonUtil.objectToJson(cjChannel));
        if (!cjChannel.isEmpty()) {
            CJ_SP_CODE = StringUtil.filterNull(cjChannel.get("acq_merchant_no"));
            CJ_MER_KEY = StringUtil.filterNull(cjChannel.get("encryption_key"));
            CJ_CHANNEL_CODE = StringUtil.filterNull(cjChannel.get("acq_org_no"));
            CJ_FEE_RATE = StringUtil.filterNull(cjChannel.get("trade_fee_rate"));
            CJ_SINGLE_FEE = StringUtil.filterNull(cjChannel.get("withdraw_single_fee"));

            CJ_SINGLE_FEE = String.valueOf(new BigDecimal(CJ_SINGLE_FEE).multiply(new BigDecimal("100")).intValue());
        }
    }

    /**
     * 畅捷获取令牌
     *
     * @return
     * @throws Exception
     */
    public static CommonResult getSpToken() throws Exception {

        log.info("--------进入畅捷获取令牌接口----------");
        try {

            String url = CJ_ACCESS_URL + "v2/base/getQkSpToken";

            TreeMap<String, Object> signParams = new TreeMap<>();
            signParams.put("spCode", CJ_SP_CODE);

            JSONObject jsonObj = new JSONObject();
            jsonObj.put("spCode", CJ_SP_CODE);
            jsonObj.put("sign", SignUtil.signByMap(CJ_MER_KEY, signParams));

            String tokenJsonReq = jsonObj.toJSONString();
            Response response = HttpUtil.sendPost(url, tokenJsonReq);

            String tokenJsonRsp = response.body().string();
            log.info("畅捷获取令牌接口返回jsonRsp: " + tokenJsonRsp);

            if (StringUtil.isBlank(tokenJsonRsp)) {
                return CommonResult.build(403, "获取令牌返回为空");
            }

            String msg = response.message();
            if (response.isSuccessful()) {

                JSONObject tokenJson = JSONObject.parseObject(tokenJsonRsp);
                String code = tokenJson.getString("code");
                String message = tokenJson.getString("message");
                JSONObject data = tokenJson.getJSONObject("data");

                if ("000000".equals(code)) {
                    return CommonResult.ok(data);
                }
                return CommonResult.build(403, message);
            }
            return CommonResult.build(403, msg);

        } catch (Exception e) {
            e.printStackTrace();
            log.info("畅捷获取令牌接口异常：" + e.getMessage());
            return CommonResult.build(403, "获取令牌异常");
        }
    }

    /**
     * 商户注册
     *
     * @return
     * @throws Exception
     */
    public static CommonResult merReg(Map<String, String> params) throws Exception {

        log.info("畅捷商户注册接口参数：" + JsonUtil.objectToJson(params));
        String merchantNo = params.get("merchantNo");
        String cardNo = params.get("cardNo");
        String idCardNo = params.get("idCardNo");
        String mobileNo = params.get("mobileNo");
        String bankAccountNo = params.get("bankAccountNo");
        String bankAccountName = params.get("bankAccountName");
        String bankName = params.get("bankName");
        String bankNo = params.get("bankNo");

        try {
            if (StringUtil.isBlank(merchantNo, cardNo, idCardNo, mobileNo, bankAccountNo, bankAccountName, bankName)) {
                return CommonResult.build(403, "必要参数不能有空");
            }
            //获取银行信息
            String bankCode = BankCache.getBankCode(Constants.PAY_ACQ_CODE_CJ, bankNo);
            String bankAbbr = BankCache.getBankName(Constants.PAY_ACQ_CODE_CJ, bankNo);
            if (StringUtils.isBlank(bankCode) || StringUtils.isBlank(bankAbbr)) {
                return CommonResult.build(403, "不支持此银行卡");
            }

            //获取令牌
            CommonResult tokenRes = getSpToken();
            if (tokenRes.getStatus() != 200) {
                return tokenRes;
            }
            JSONObject tokenJson = (JSONObject) tokenRes.getData();
            String token = tokenJson.getString("token");
            if (StringUtils.isBlank(token)) {
                return CommonResult.build(403, "获取令牌为空");
            }
            // 解密令牌
            String tokenClearText = EncryptUtil.desDecrypt(token, CJ_MER_KEY);

            // 敏感数据3DES加密
            String bankAccountNoCipher = EncryptUtil.desEncrypt(bankAccountNo, CJ_MER_KEY);
            String mobileNoCipher = EncryptUtil.desEncrypt(mobileNo, CJ_MER_KEY);
            String idCardNoCipher = EncryptUtil.desEncrypt(idCardNo, CJ_MER_KEY);

            String url = CJ_ACCESS_URL + "v2/merchant/merchantReg";

            TreeMap<String, Object> signParams = new TreeMap<>();
            signParams.put("token", tokenClearText);
            signParams.put("spCode", CJ_SP_CODE);
            signParams.put("channelCode", CJ_CHANNEL_CODE);
            signParams.put("merName", merchantNo);
            signParams.put("merAbbr", RandomUtil.getRandomNumbers(4));
            signParams.put("idCardNo", idCardNo);
            signParams.put("bankAccountNo", bankAccountNo);//银行卡号
            signParams.put("mobile", mobileNo);
            signParams.put("bankAccountName", bankAccountName);//开户名
            signParams.put("bankAccountType", "2");
            signParams.put("bankName", bankName);//银行名称
            signParams.put("bankSubName", bankName);//银行名称
            signParams.put("bankCode", bankCode);//银行编码
            signParams.put("bankAbbr", bankAbbr);//银行代码
            signParams.put("bankChannelNo", bankNo);//联行号
            signParams.put("bankProvince", "广东省");
            signParams.put("bankCity", "深圳市");
            signParams.put("debitRate", CJ_FEE_RATE);
            signParams.put("debitCapAmount", "99999900");
            signParams.put("creditRate", CJ_FEE_RATE);
            signParams.put("creditCapAmount", "99999900");
            signParams.put("withdrawDepositRate", "0");
            signParams.put("withdrawDepositSingleFee", CJ_SINGLE_FEE);
            signParams.put("reqFlowNo", DateUtil.getDate("yyyyMMddHHmmss"));

            JSONObject jsonObj = JSON.parseObject(JsonUtil.objectToJson(signParams));
            jsonObj.put("sign", SignUtil.signByMap(CJ_MER_KEY, signParams));
            jsonObj.put("bankAccountNo", bankAccountNoCipher);
            jsonObj.put("mobile", mobileNoCipher);
            jsonObj.put("idCardNo", idCardNoCipher);

            String jsonReq = jsonObj.toJSONString();
            Response response = HttpUtil.sendPost(url, jsonReq);

            String jsonRsp = response.body().string();
            log.info(merchantNo + "/" + cardNo + "畅捷商户注册接口返回jsonRsp: " + jsonRsp);

            if (StringUtil.isBlank(jsonRsp)) {
                return CommonResult.build(403, "商户注册返回为空");
            }

            String msg = response.message();
            if (response.isSuccessful()) {

                JSONObject json = JSONObject.parseObject(jsonRsp);
                String code = json.getString("code");
                String message = json.getString("message");
                JSONObject data = json.getJSONObject("data");

                if ("000000".equals(code)) {

                    //另开线程新增直清商户记录
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                String zyZqMerNo = data.getString("merchantCode");

                                ZqMerchantService zqMerchantService = SpringUtil.getBean("zqMerchantServiceImpl");

                                ZqMerchant zqMerchant = new ZqMerchant();
                                zqMerchant.setReportNo(WebUtil.nextUniqueSeqNo("t_zq_merchant_info", "CJ_MER", 25));
                                zqMerchant.setMerchantNo(merchantNo);
                                zqMerchant.setAcqCode(Constants.PAY_ACQ_CODE_CJ);
                                zqMerchant.setCardNo(cardNo);
                                zqMerchant.setZqMerchantNo(zyZqMerNo);
                                zqMerchant.setRespCode(code);
                                zqMerchant.setRespMsg(msg);
                                zqMerchant.setZqStatus(Constants.ZQ_MER_STATUS_SUCC);
                                zqMerchant.setEffectiveStatus(Constants.ZQ_MER_EFFECTIVE_STATUS_SUCC);

                                int count = zqMerchantService.saveZqMerchant(zqMerchant);
                                log.info(merchantNo + "/" + cardNo + "新增畅捷直清商户记录影响的行数：" + count);

                            } catch (Exception e) {
                                e.printStackTrace();
                                log.info(merchantNo + "/" + cardNo + "新增畅捷直清商户记录异常：" + e);
                            }
                        }
                    }).start();

                    return CommonResult.ok(data);
                }
                return CommonResult.build(403, message);
            }
            return CommonResult.build(403, msg);

        } catch (Exception e) {
            e.printStackTrace();
            log.info(merchantNo + "/" + cardNo + "畅捷商户注册接口异常：" + e.getMessage());
            return CommonResult.build(403, "商户注册异常");
        }
    }

    /**
     * 银行卡绑卡短信
     *
     * @return
     * @throws Exception
     */
    public static CommonResult merBindCardSignSms(Map<String, String> params) throws Exception {

        log.info("畅捷银行卡绑卡短信接口参数：" + JsonUtil.objectToJson(params));

        String merchantNo = params.get("merchantNo");
        String cardNo = params.get("cardNo");
        String merchantCode = params.get("merchantCode");
        String orderNo = params.get("orderNo");
        String bankAccountNo = params.get("bankAccountNo");
        String bankAccountName = params.get("bankAccountName");
        String bankNo = params.get("bankNo");
        String idCardNo = params.get("idCardNo");
        String mobileNo = params.get("mobileNo");
        try {
            if (StringUtil.isBlank(merchantNo, cardNo, merchantCode, orderNo, bankAccountNo, bankAccountName, bankNo, idCardNo, mobileNo)) {
                return CommonResult.build(403, "必要参数不能有空");
            }
            //获取银行信息
            String cjChannelCode = BankCache.getBak1(Constants.PAY_ACQ_CODE_CJ, bankNo);
            if (StringUtils.isBlank(cjChannelCode)) {
                return CommonResult.build(403, "不支持此银行卡");
            }
            //获取令牌
            CommonResult tokenRes = getSpToken();
            if (tokenRes.getStatus() != 200) {
                return tokenRes;
            }
            JSONObject tokenJson = (JSONObject) tokenRes.getData();
            String token = tokenJson.getString("token");
            if (StringUtils.isBlank(token)) {
                return CommonResult.build(403, "获取令牌为空");
            }
            // 解密令牌
            String tokenClearText = EncryptUtil.desDecrypt(token, CJ_MER_KEY);

            // 敏感数据3DES加密
            String bankAccountNoCipher = EncryptUtil.desEncrypt(bankAccountNo, CJ_MER_KEY);
            String mobileNoCipher = EncryptUtil.desEncrypt(mobileNo, CJ_MER_KEY);
            String idCardNoCipher = EncryptUtil.desEncrypt(idCardNo, CJ_MER_KEY);

            String url = CJ_ACCESS_URL + "v2/sign/merchantSignSms";

            TreeMap<String, Object> signParams = new TreeMap<>();
            signParams.put("token", tokenClearText);
            signParams.put("spCode", CJ_SP_CODE);
            signParams.put("channelCode", cjChannelCode);
            signParams.put("orderNo", orderNo);
            signParams.put("merchantCode", merchantCode);
            signParams.put("bankAccountName", bankAccountName);//开户名
            signParams.put("bankAccountNo", bankAccountNo);//银行卡号
            signParams.put("idCardNo", idCardNo);
            signParams.put("mobile", mobileNo);

            JSONObject jsonObj = JSON.parseObject(JsonUtil.objectToJson(signParams));
            jsonObj.put("sign", SignUtil.signByMap(CJ_MER_KEY, signParams));
            jsonObj.put("bankAccountNo", bankAccountNoCipher);
            jsonObj.put("mobile", mobileNoCipher);
            jsonObj.put("idCardNo", idCardNoCipher);

            String jsonReq = jsonObj.toJSONString();
            Response response = HttpUtil.sendPost(url, jsonReq);

            String jsonRsp = response.body().string();
            log.info(merchantNo + "/" + cardNo + "畅捷银行卡绑卡短信接口返回jsonRsp: " + jsonRsp);

            if (StringUtil.isBlank(jsonRsp)) {
                return CommonResult.build(403, "银行卡绑卡短信返回为空");
            }

            String msg = response.message();
            if (response.isSuccessful()) {

                JSONObject json = JSONObject.parseObject(jsonRsp);
                String code = json.getString("code");
                String message = json.getString("message");
                JSONObject data = json.getJSONObject("data");

                if ("000000".equals(code)) {

                    //另开线程新增绑卡记录
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                String bindRespCode = data.getString("respCode");
                                String bindRespMsg = data.getString("respMsg");
                                String bindStatus = data.getString("signStatus");

                                BindCardService bindCardService = SpringUtil.getBean("bindCardServiceImpl");

                                Map<String, String> map = new HashMap<>();
                                map.put("bindNo", orderNo);
                                map.put("acqCode", Constants.PAY_ACQ_CODE_CJ);
                                map.put("merchantNo", merchantNo);
                                map.put("cardNo", cardNo);
                                map.put("accountNo", bankAccountNo);
                                map.put("accountName", bankAccountName);
                                map.put("mobileNo", mobileNo);
                                map.put("idCardNo", idCardNo);
                                map.put("respCode", bindRespCode + "[" + bindRespMsg + "]");
                                map.put("respMsg", bindStatus);

                                int count = bindCardService.saveBindCardRecord(map);
                                log.info(merchantNo + "/" + cardNo + "新增畅捷绑卡记录影响的行数：" + count);

                            } catch (Exception e) {
                                e.printStackTrace();
                                log.info(merchantNo + "/" + cardNo + "新增畅捷绑卡记录异常：" + e);
                            }
                        }
                    }).start();

                    return CommonResult.ok(data);
                }
                return CommonResult.build(403, message);
            }
            return CommonResult.build(403, msg);

        } catch (Exception e) {
            e.printStackTrace();
            log.info(merchantNo + "/" + cardNo + "畅捷银行卡绑卡短信接口异常：" + e.getMessage());
            return CommonResult.build(403, "银行卡绑卡短信异常");
        }
    }

    /**
     * 银行卡绑卡
     *
     * @return
     * @throws Exception
     */
    public static CommonResult merBindCardSign(Map<String, String> params) throws Exception {

        log.info("畅捷银行卡绑卡接口参数：" + JsonUtil.objectToJson(params));
        String merchantNo = params.get("merchantNo");
        String cardNo = params.get("cardNo");
        String merchantCode = params.get("merchantCode");
        String orderNo = params.get("orderNo");
        String bankAccountNo = params.get("bankAccountNo");
        String bankAccountName = params.get("bankAccountName");
        String bankNo = params.get("bankNo");
        String idCardNo = params.get("idCardNo");
        String mobileNo = params.get("mobileNo");
        String cvn2 = params.get("cvn2");
        String expired = params.get("expired");
        String smsCode = params.get("smsCode");

        try {
            if (StringUtil.isBlank(merchantNo, merchantCode, orderNo, bankAccountNo, bankAccountName, bankNo, idCardNo, mobileNo, cvn2, expired, smsCode)) {
                return CommonResult.build(403, "必要参数不能有空");
            }
            //获取银行信息
            String cjChannelCode = BankCache.getBak1(Constants.PAY_ACQ_CODE_CJ, bankNo);
            if (StringUtils.isBlank(cjChannelCode)) {
                return CommonResult.build(403, "不支持此银行卡");
            }
            //获取令牌
            CommonResult tokenRes = getSpToken();
            if (tokenRes.getStatus() != 200) {
                return tokenRes;
            }
            JSONObject tokenJson = (JSONObject) tokenRes.getData();
            String token = tokenJson.getString("token");
            if (StringUtils.isBlank(token)) {
                return CommonResult.build(403, "获取令牌为空");
            }
            // 解密令牌
            String tokenClearText = EncryptUtil.desDecrypt(token, CJ_MER_KEY);

            //有效期yyMM格式
            String expiredCopy = new String(expired);
            String cardYear = expiredCopy.substring(2, 4);
            String cardMonth = expired.substring(0, 2);
            expired = cardYear + cardMonth;

            // 敏感数据3DES加密
            String bankAccountNoCipher = EncryptUtil.desEncrypt(bankAccountNo, CJ_MER_KEY);
            String mobileNoCipher = EncryptUtil.desEncrypt(mobileNo, CJ_MER_KEY);
            String idCardNoCipher = EncryptUtil.desEncrypt(idCardNo, CJ_MER_KEY);
            String cvn2Cipher = EncryptUtil.desEncrypt(cvn2, CJ_MER_KEY);
            String expiredCipher = EncryptUtil.desEncrypt(expired, CJ_MER_KEY);

            String url = CJ_ACCESS_URL + "v2/sign/merchantSign";

            TreeMap<String, Object> signParams = new TreeMap<>();
            signParams.put("token", tokenClearText);
            signParams.put("spCode", CJ_SP_CODE);
            signParams.put("channelCode", cjChannelCode);
            signParams.put("orderNo", orderNo);
            signParams.put("merchantCode", merchantCode);
            signParams.put("bankAccountName", bankAccountName);//开户名
            signParams.put("bankAccountNo", bankAccountNo);//银行卡号
            signParams.put("idCardNo", idCardNo);
            signParams.put("mobile", mobileNo);
            signParams.put("cvn2", cvn2);
            signParams.put("expired", expired);
            signParams.put("smsCode", smsCode);
            signParams.put("isNeedSms", "1");

            JSONObject jsonObj = JSON.parseObject(JsonUtil.objectToJson(signParams));
            jsonObj.put("sign", SignUtil.signByMap(CJ_MER_KEY, signParams));
            jsonObj.put("bankAccountNo", bankAccountNoCipher);
            jsonObj.put("mobile", mobileNoCipher);
            jsonObj.put("idCardNo", idCardNoCipher);
            jsonObj.put("cvn2", cvn2Cipher);
            jsonObj.put("expired", expiredCipher);

            String jsonReq = jsonObj.toJSONString();
            Response response = HttpUtil.sendPost(url, jsonReq);

            String jsonRsp = response.body().string();
            log.info(merchantNo + "/" + cardNo + "畅捷银行卡绑卡接口返回jsonRsp: " + jsonRsp);

            if (StringUtil.isBlank(jsonRsp)) {
                return CommonResult.build(403, "银行卡绑卡返回为空");
            }

            String msg = response.message();
            if (response.isSuccessful()) {

                JSONObject json = JSONObject.parseObject(jsonRsp);
                String code = json.getString("code");
                String message = json.getString("message");
                JSONObject data = json.getJSONObject("data");

                if ("000000".equals(code)) {
                    return CommonResult.ok(data);
                }
                return CommonResult.build(403, message);
            }
            return CommonResult.build(403, msg);

        } catch (Exception e) {
            e.printStackTrace();
            log.info(merchantNo + "/" + cardNo + "畅捷银行卡绑卡接口异常：" + e.getMessage());
            return CommonResult.build(403, "银行卡绑卡异常");
        }
    }

    /**
     * 银行卡消费
     *
     * @return
     * @throws Exception
     */
    public static CommonResult merConsume(Map<String, String> params) throws Exception {

        log.info("畅捷银行卡消费接口参数：" + JsonUtil.objectToJson(params));
        String merchantNo = params.get("merchantNo");
        String cardNo = params.get("cardNo");
        String merchantCode = params.get("merchantCode");
        String orderNo = params.get("orderNo");
        String orderAmount = params.get("amount");
        String bankAccountNo = params.get("bankAccountNo");
        String bankAccountName = params.get("bankAccountName");
        String bankNo = params.get("bankNo");
        String idCardNo = params.get("idCardNo");
        String mobileNo = params.get("mobileNo");
        String cvn2 = params.get("cvn2");
        String expired = params.get("expired");

        try {
            if (StringUtil.isBlank(merchantNo, merchantCode, orderNo, orderAmount, bankAccountNo, bankAccountName, bankNo, idCardNo, mobileNo, cvn2, expired)) {
                return CommonResult.build(403, "必要参数不能有空");
            }
            //获取银行信息
            String cjChannelCode = BankCache.getBak1(Constants.PAY_ACQ_CODE_CJ, bankNo);
            if (StringUtils.isBlank(cjChannelCode)) {
                return CommonResult.build(403, "不支持此银行卡");
            }
            //获取令牌
            CommonResult tokenRes = getSpToken();
            if (tokenRes.getStatus() != 200) {
                return tokenRes;
            }
            JSONObject tokenJson = (JSONObject) tokenRes.getData();
            String token = tokenJson.getString("token");
            if (StringUtils.isBlank(token)) {
                return CommonResult.build(403, "获取令牌为空");
            }
            // 解密令牌
            String tokenClearText = EncryptUtil.desDecrypt(token, CJ_MER_KEY);

            orderAmount = String.valueOf(new BigDecimal(orderAmount).multiply(new BigDecimal("100")).intValue());
            //有效期yyMM格式
            String expiredCopy = new String(expired);
            String cardYear = expiredCopy.substring(2, 4);
            String cardMonth = expired.substring(0, 2);
            expired = cardYear + cardMonth;

            // 敏感数据3DES加密
            String bankAccountNoCipher = EncryptUtil.desEncrypt(bankAccountNo, CJ_MER_KEY);
            String mobileNoCipher = EncryptUtil.desEncrypt(mobileNo, CJ_MER_KEY);
            String idCardNoCipher = EncryptUtil.desEncrypt(idCardNo, CJ_MER_KEY);
            String cvn2Cipher = EncryptUtil.desEncrypt(cvn2, CJ_MER_KEY);
            String expiredCipher = EncryptUtil.desEncrypt(expired, CJ_MER_KEY);

            String url = CJ_ACCESS_URL + "v2/trans/merchantConsume";

            TreeMap<String, Object> signParams = new TreeMap<>();
            signParams.put("token", tokenClearText);
            signParams.put("spCode", CJ_SP_CODE);
            signParams.put("channelCode", cjChannelCode);
            signParams.put("orderNo", orderNo);
            signParams.put("orderAmount", orderAmount);
            signParams.put("merchantCode", merchantCode);
            signParams.put("bankAccountName", bankAccountName);//开户名
            signParams.put("bankAccountNo", bankAccountNo);//银行卡号
            signParams.put("idCardNo", idCardNo);
            signParams.put("mobile", mobileNo);
            signParams.put("cvn2", cvn2);
            signParams.put("expired", expired);
            signParams.put("isNeedSms", "0");
            signParams.put("isNeedSign", "1");
            signParams.put("productName", merchantNo);
            signParams.put("productDesc", merchantNo);

            JSONObject jsonObj = JSON.parseObject(JsonUtil.objectToJson(signParams));
            jsonObj.put("sign", SignUtil.signByMap(CJ_MER_KEY, signParams));
            jsonObj.put("bankAccountNo", bankAccountNoCipher);
            jsonObj.put("mobile", mobileNoCipher);
            jsonObj.put("idCardNo", idCardNoCipher);
            jsonObj.put("cvn2", cvn2Cipher);
            jsonObj.put("expired", expiredCipher);

            String jsonReq = jsonObj.toJSONString();
            Response response = HttpUtil.sendPost(url, jsonReq);

            String jsonRsp = response.body().string();
            log.info(merchantNo + "/" + cardNo + "/" + orderNo + "畅捷银行卡消费接口返回jsonRsp: " + jsonRsp);

            if (StringUtil.isBlank(jsonRsp)) {
                return CommonResult.build(403, "银行卡消费返回为空");
            }

            String msg = response.message();
            if (response.isSuccessful()) {

                JSONObject json = JSONObject.parseObject(jsonRsp);
                String code = json.getString("code");
                String message = json.getString("message");
                JSONObject data = json.getJSONObject("data");

                if (!"000000".equals(code)) {
                    data = new JSONObject();
                    data.put("respCode", code);
                    data.put("respMsg", message);
                }
                return CommonResult.ok(data);
            }
            return CommonResult.build(403, msg);

        } catch (Exception e) {
            e.printStackTrace();
            log.info(merchantNo + "/" + cardNo + "/" + orderNo + "畅捷银行卡消费接口异常：" + e.getMessage());
            return CommonResult.build(403, "银行卡消费异常");
        }
    }


    /**
     * 订单状态查询
     *
     * @return
     * @throws Exception
     */
    public static CommonResult queryOrder(Map<String, String> params) throws Exception {

        log.info("畅捷订单状态查询接口参数：" + JsonUtil.objectToJson(params));
        String merchantCode = params.get("merchantCode");
        String orderNo = params.get("orderNo");

        try {
            if (StringUtil.isBlank(merchantCode, orderNo)) {
                return CommonResult.build(403, "必要参数不能有空");
            }
            //获取令牌
            CommonResult tokenRes = getSpToken();
            if (tokenRes.getStatus() != 200) {
                return tokenRes;
            }
            JSONObject tokenJson = (JSONObject) tokenRes.getData();
            String token = tokenJson.getString("token");
            if (StringUtils.isBlank(token)) {
                return CommonResult.build(403, "获取令牌为空");
            }
            // 解密令牌
            String tokenClearText = EncryptUtil.desDecrypt(token, CJ_MER_KEY);

            String url = CJ_ACCESS_URL + "v2/trans/consumeQuery";

            TreeMap<String, Object> signParams = new TreeMap<>();
            signParams.put("token", tokenClearText);
            signParams.put("spCode", CJ_SP_CODE);
            signParams.put("orderNo", orderNo);
            signParams.put("merchantCode", merchantCode);

            JSONObject jsonObj = JSON.parseObject(JsonUtil.objectToJson(signParams));
            jsonObj.put("sign", SignUtil.signByMap(CJ_MER_KEY, signParams));

            String jsonReq = jsonObj.toJSONString();
            Response response = HttpUtil.sendPost(url, jsonReq);

            String jsonRsp = response.body().string();
            log.info(orderNo + "畅捷订单状态查询接口返回jsonRsp: " + jsonRsp);

            if (StringUtil.isBlank(jsonRsp)) {
                return CommonResult.build(403, "订单状态查询返回为空");
            }

            String msg = response.message();
            if (response.isSuccessful()) {

                JSONObject json = JSONObject.parseObject(jsonRsp);
                String code = json.getString("code");
                String message = json.getString("message");
                JSONObject data = json.getJSONObject("data");

                if ("000000".equals(code)) {
                    return CommonResult.ok(data);
                }
                return CommonResult.build(403, message);
            }
            return CommonResult.build(403, msg);

        } catch (Exception e) {
            e.printStackTrace();
            log.info(orderNo + "畅捷订单状态查询接口异常：" + e.getMessage());
            return CommonResult.build(403, "订单状态查询异常");
        }
    }
}